package com.whiteape.book.ui.fragment;

import android.os.Bundle;
import android.view.View;

import androidx.appcompat.app.AlertDialog;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.whiteape.book.R;
import com.whiteape.book.common.RxEvent;
import com.whiteape.book.contract.DownloadContract;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.DownloadTaskBean;
import com.whiteape.book.model.type.DownloadStatus;
import com.whiteape.book.model.type.MediaType;
import com.whiteape.book.presenter.DownloadPresenter;
import com.whiteape.book.service.DownloadService;
import com.whiteape.book.ui.activity.BookReadActivity;
import com.whiteape.book.ui.activity.ComicReadActivity;
import com.whiteape.book.ui.adapter.DownloadAdapter;
import com.whiteape.book.ui.base.BaseRVMVPFragment;
import com.whiteape.book.utils.ToastUtils;
import com.whiteape.book.widget.RefreshLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

public class DownloadFragment extends BaseRVMVPFragment<DownloadContract.Presenter, DownloadTaskBean>
        implements DownloadContract.View, DownloadService.IDownloadListener {

    private DownloadAdapter mAdapter;
    private List<DownloadTaskBean> mData = new ArrayList<>();
    private int mediaType = MediaType.MEDIA_TYPE_NOVEL;
    public static final String EXTRA_MEDIA_TYPE = "extra_media_type";

    @BindView(R.id.refresh_layout_loading)
    RefreshLayout refreshLayout;

    public static DownloadFragment newInstance(int mediaType) {
        Bundle args = new Bundle();
        args.putInt(EXTRA_MEDIA_TYPE, mediaType);
        DownloadFragment downloadFragment = new DownloadFragment();
        downloadFragment.setArguments(args);
        return downloadFragment;

    }

    public DownloadFragment() {
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        mSmartRefreshLayout.setEnableRefresh(false);
    }

    @Override
    public void finishRefresh(List<DownloadTaskBean> beanList) {
        refreshLayout.showFinish();
        mData.clear();
        mData.addAll(beanList);
        refresh();

    }

    @Override
    protected void initEvent() {
        super.initEvent();
    }

    @Override
    protected DownloadContract.Presenter bindPresenter() {
        return new DownloadPresenter();
    }

    @Override
    public void showError() {

        refreshLayout.showError();
    }

    @Override
    public void complete() {
        refreshLayout.showFinish();

    }


    @Override
    protected boolean setBatchDeleteEnabled() {
        return true;
    }

    @Override
    protected boolean setAdapterModeSwitchEnabled() {
        return false;
    }

    @Override
    protected boolean showTotal() {
        return false;
    }

    @Override
    protected boolean setMoveEnabled() {
        return false;
    }

    @Override
    protected boolean initListOrGrid() {
        return true;
    }

    @Override
    protected List<BaseQuickAdapter<DownloadTaskBean, BaseViewHolder>> setAdapter() {
        mAdapter = new DownloadAdapter(R.layout.item_download, mData);
        mAdapter.setSelectedList(mSelectedList);
        return Collections.singletonList(mAdapter);
    }

    @Override
    protected void deleteItems(List<DownloadTaskBean> itemList) {
        if (getContext() != null) {

            new AlertDialog.Builder(getContext()).setTitle(R.string.wa_common_tip)
                    .setMessage(R.string.sure_to_clear_local)
                    .setNeutralButton(R.string.wa_common_cancel, (dialog, which) -> {
                        dialog.dismiss();
                    })
                    .setPositiveButton(R.string.wa_common_delete, (dialog, which) -> {
//                        List<String> mediaIdList = new ArrayList<>();
//                        for (DownloadTaskBean taskBean : itemList) {
//                            mediaIdList.add(taskBean.getMediaId());
//                        }
                        MediaStorageManager.getInstance().deleteDownloadedFile(itemList);
                        doDeleteItems(itemList);
                        RxBus.get().post(RxEvent.DOWNLOADED_FILE_DELETED, itemList);
                        ToastUtils.show("清理完毕");
                    })
                    .setNegativeButton(R.string.wa_common_not_delete, (dialog, which) -> {
                        dialog.dismiss();
                        doDeleteItems(itemList);
                        RxBus.get().post(RxEvent.DOWNLOADED_FILE_DELETED, itemList);
                    })
                    .show();
        }


    }

    private void doDeleteItems(List<DownloadTaskBean> itemList) {
        MediaStorageManager.getInstance().deleteDownloadTaskList(itemList);
        mData.removeAll(itemList);
        RxBus.get().post(RxEvent.DOWNLOAD_TASK_REMOVED, itemList);
        refresh();
    }

    @Override
    protected void onItemClickListener(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    protected void onItemChildClickListener(BaseQuickAdapter adapter, View view, int position) {
        DownloadTaskBean downloadTaskBean = mData.get(position);
        if (view.getId() == R.id.download_rl_left || view.getId() == R.id.fl_img) {
            //阅读
            String mediaId = downloadTaskBean.getMediaId();
            CollectionMediaBean collectionMediaBean = MediaStorageManager.getInstance().getShelfMedia(mediaId);
            int mediaType = collectionMediaBean.getMediaType();

            if (getContext() == null) {
                return;
            }
            if (mediaType == MediaType.MEDIA_TYPE_NOVEL) {
                BookReadActivity.startActivity(getContext(), collectionMediaBean, true, -1);
            } else if (mediaType == MediaType.MEDIA_TYPE_COMIC) {
                ComicReadActivity.startActivity(getContext(), collectionMediaBean, null, true, null);
            }

        } else if (view.getId() == R.id.download_rl_right) {
            if (downloadTaskBean.getStatus() == DownloadStatus.STATUS_DOWNLOADING) {
                downloadTaskBean.setStatus(DownloadStatus.STATUS_PAUSE);
            } else if (downloadTaskBean.getStatus() == DownloadStatus.STATUS_PAUSE ||
            downloadTaskBean.getStatus() == DownloadStatus.STATUS_ERROR) {
                downloadTaskBean.setStatus(DownloadStatus.STATUS_DOWNLOADING);
            }
            RxBus.get().post(RxEvent.DOWNLOAD_STATUS_CHANGED, downloadTaskBean);
            mAdapter.notifyItemChanged(position);
        }

    }

    @Override
    protected void onSelectStateChanged(boolean selectStateEnable) {
        mAdapter.setSelectMode(selectStateEnable);

    }

    @Override
    public void onDownloadStatusChanged(DownloadTaskBean task) {
        if (getActivity() == null || isDetached() ||isRemoving()) {
            return;
        }
        //可能是其他线程调过来的
        getActivity().runOnUiThread(() -> {
            for (int i = 0; i < mData.size(); i++) {
                DownloadTaskBean bean = mData.get(i);
                if (bean.getTaskName().equals(task.getTaskName())) {
                    mAdapter.notifyItemChanged(i);
                }
            }
        });
    }



    @Subscribe(thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxEvent.DOWNLOAD_TASK_ADD),
                    @Tag(RxEvent.DOWNLOAD_TASK_REMOVED)})
    public void addDownloadTaskBean(DownloadTaskBean bean) {
        mPresenter.refreshDownloadTask();
    }
}
